<template>
  <div class="app-container">


    <el-row :gutter="10" class="mb8">

    </el-row>

      <div slot="header" class="clearfix">
        <span>钱包流水</span>
      </div>
    <div>
      <el-tabs class="center-tabs" v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部记录" name="all" />
        <el-tab-pane label="充值记录" name="recharge" />
        <el-tab-pane label="下单记录" name="order" />
      </el-tabs>
    </div>



      <el-table v-loading="loading" :data="dealCompanyList">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="司机姓名" align="center" prop="userName"/>
<!--        TODO 充值钱包添加记录金额操作-->
        <el-table-column label="联系电话" align="center" prop="userPhone"/>
        <el-table-column label="变动量(kg)" align="center" prop="dealAmount">
          <template slot-scope="scope">
           {{ mlToL(scope.row.dealAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="业务类型" align="center" prop="dealType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.c_deal_type" :value="scope.row.dealType"/>
          </template>
        </el-table-column>
        <el-table-column label="发票文件" align="center" prop="invoiceFile">
          <template slot-scope="scope">
            <template v-if="scope.row.status !== 0">
              <el-link v-if="scope.row.invoiceFile" @click="handleDownload(scope.row)" target="_blank" type="primary" icon="el-icon-download">下载发票文件</el-link>
              <el-link v-else-if="scope.row.invoiceStatus === 1">未上传发票文件</el-link>
            </template>
          </template>
        </el-table-column>


        <el-table-column label="交易时间" align="center" prop="createTime"/>
<!--        <el-table-column label="发票状态" align="center" prop="invoiceStatus">-->
<!--          <template slot-scope="scope">-->
<!--&lt;!&ndash;            如果是0为未申请&ndash;&gt;-->
<!--            <el-tag v-if="scope.row.invoiceStatus == 0" type="warning">未申请</el-tag>-->
<!--&lt;!&ndash;            如果是1为已申请&ndash;&gt;-->
<!--            <el-tag v-if="scope.row.invoiceStatus == 1" type="success">已申请</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="申请状态" align="center" prop="status">
          <template slot-scope="scope">
            <template v-if="scope.row.status !== undefined">
              <dict-tag :options="dict.type.c_apply_invoice" :value="scope.row.status"/>
            </template>
            <template v-else>
              <el-tag type="warning">未申请</el-tag>
            </template>
          </template>
        </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="scope.row.invoiceStatus == 1 ? handleUpdate(scope.row) : replayInvoice(scope.row)"
            v-hasRole="['common','admin','dragon']"
          >
            {{ scope.row.invoiceStatus == 1 ? '发票详情' : '申请开票' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDealList"
    />

    <!-- 添加或修改发票对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">

      <el-table v-if="this.form.invoiceId === null" v-loading="loading" :data="headerList" @row-click="handleRowClick">
        <el-table-column label="发票类型" align="center" prop="invoiceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.c_invoice" :value="scope.row.invoiceType"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="公司抬头名称" align="center" prop="invoiceTitle" />-->
        】     <el-table-column label="税号" align="center" prop="invoiceTaxNo" />
        <el-table-column label="公司地址" align="center" prop="companyAddress" />
        <el-table-column label="联系人" align="center" prop="contacts" />
        <el-table-column label="公司电话" align="center" prop="companyPhone" />
        <el-table-column label="联系电话" align="center" prop="contactsPhone" />
        <el-table-column label="开户银行" align="center" prop="bankName" />
        <el-table-column label="银行帐号" align="center" prop="bankAccount" />
        <el-table-column label="银行行号" align="center" prop="bankNum" />

        </el-table>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发票类型" prop="invoiceType">
          <el-radio-group v-model="form.invoiceType">
            <el-radio
              v-for="dict in dict.type.c_invoice"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公司全称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
<!--                <el-form-item label="公司抬头名称" prop="invoiceTitle">-->
<!--                  <el-input v-model="form.invoiceTitle" placeholder="请输入抬头名称" />-->
<!--                </el-form-item>-->
        <!--        <el-form-item label="抬头内容">-->
        <!--          <el-input type="textarea" v-model="form.invoiceContent" :min-height="192"/>-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="发票金额(元)" prop="invoiceAmount">-->
<!--          <el-input v-model="form.invoiceAmount" placeholder="请输入发票金额(元)"/>-->
<!--        </el-form-item>-->
        <el-form-item label="信用代码" prop="invoiceTaxNo">
          <el-input v-model="form.invoiceTaxNo" placeholder="请输入信用代码"/>
        </el-form-item>
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input v-model="form.companyAddress" placeholder="请输入公司地址"/>
        </el-form-item>
<!--        开票金额-->
        <el-form-item label="发票金额(元)" prop="invoiceAmount">
          <el-input v-model="form.invoiceAmount" placeholder="请输入发票金额(元)"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人"/>
        </el-form-item>
        <el-form-item label="公司电话" prop="companyPhone">
          <el-input v-model="form.companyPhone" placeholder="请输入公司电话"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactsPhone">
          <el-input v-model="form.contactsPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户银行"/>
        </el-form-item>
        <el-form-item label="银行帐号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行帐号"/>
        </el-form-item>
        <el-form-item label="银行行号" prop="bankNum">
          <el-input v-model="form.bankNum" placeholder="请输入银行行号"/>
        </el-form-item>
        <!--        <el-form-item label="开票税金" prop="invoiceTax">-->
        <!--          <el-input v-model="form.invoiceTax" placeholder="请输入开票税金"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getInvoice, delInvoice,  updateInvoice } from "@/api/consumer/invoice";
import {listInvoice, addInvoice,updateInvoiceStatus} from '@/api/consumer/admin/invoice'
import {getCompanyWalletDeal} from "@/api/consumer/admin/comWallet";
import {getWalletCompany} from "@/api/consumer/walletCompany";
import { listHeader, getHeader, delHeader, addHeader, updateHeader } from "@/api/consumer/header";
import {fenToYuan, mlToL} from "../../../utils/unitUtil";

export default {
  name: "Invoice",
  dicts: ['c_invoice', 'c_apply_invoice', 'c_deal_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票表格数据
      invoiceList: [],
      // 发票抬头表格数据
      headerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // activeTab用于控制当前选中的tab
      activeTab: 'all',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        companyId: null,
        userId: null,
        invoiceType: null,
        invoiceTitle: null,
        invoiceContent: null,
        invoiceAmount: null,
        invoiceTaxNo: null,
        invoiceTax: null,
        companyName: null,
        invoiceFile: null,
        companyAddress: null,
        contacts: null,
        companyPhone: null,
        contactsPhone: null,
        bankName: null,
        bankAccount: null,
        bankNum: null,
        isDelete: null,
        status: null
      },
      // 表单参数
      form: {},
      // 公司钱包流水记录表格数据
      dealCompanyList: [],
      // 抬头选中数据
      selectedHeader: null,
      // 表单校验
      rules: {
        invoiceAmount: [
          { required: true, message: "发票金额不能为空", trigger: "blur" },
          { pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: "发票金额格式不正确", trigger: "blur" }
        ],
        //   校验电话号码
        companyPhone: [
          { required: true, message: "公司电话不能为空", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "公司电话格式不正确", trigger: "blur" }
        ],
        contactsPhone: [
          // { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式不正确", trigger: "blur" }
        ],
        invoiceTaxNo: [
          { required: true, message: "信用代码不能为空", trigger: "blur" },
          { pattern: /^[A-Z0-9]{18}$/, message: "信用代码格式不正确", trigger: "blur" }
        ],
        bankAccount: [
          { required: true, message: "银行帐号不能为空", trigger: "blur" },
          { pattern: /^[0-9]{16,19}$/, message: "银行帐号格式不正确", trigger: "blur" }
        ],
        bankNum: [
          // { required: true, message: "银行行号不能为空", trigger: "blur" },
          { pattern: /^[0-9]{12,15}$/, message: "银行行号格式不正确", trigger: "blur" }
        ],
        bankName: [
          { required: true, message: "开户银行不能为空", trigger: "blur" }
        ],
        companyName: [
          { required: true, message: "公司全称不能为空", trigger: "blur" }
        ],
        companyAddress: [
          { required: true, message: "公司地址不能为空", trigger: "blur" }
        ],
        contacts: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        invoiceType: [
          { required: true, message: "发票类型不能为空", trigger: "change" }
        ],
        invoiceTitle: [
          { required: true, message: "发票抬头名称不能为空", trigger: "blur" }
        ],
        invoiceContent: [
          { required: true, message: "发票抬头内容不能为空", trigger: "blur" }
        ],
        status: [
          {required: true, message: "申请状态不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDealList();
    this.getHeaderList();
  },
  methods: {
    mlToL,
    /** tab点击事件 切换列表*/
    handleTabClick(tab) {
      // 处理tab点击事件
      this.activeTab = tab.name;
      // ... 根据点击的tab刷新数据 ...
      if (tab.name === 'all') {
        this.queryParams.dealType = null;
        this.getDealList();
      } else if (tab.name === 'recharge') {
        this.queryParams.dealType = 1;
        this.getDealList();
      } else if (tab.name === 'order') {
        this.queryParams.dealType = 2;
        this.getDealList();
      }
      this.queryParams.dealType = null;
    },
    /** 查询发票抬头列表 */
    getHeaderList() {
      this.loading = true;
      listHeader(this.queryParams).then(response => {
        this.headerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询公司钱包流水记录列表 */
    getDealList() {
      this.loading = true;
      getCompanyWalletDeal(this.queryParams).then(response => {
        // 根据当前的 activeTab 来保留 dealType 的值
        if (this.activeTab === 'all') {
          this.queryParams.dealType = null;
        } else if (this.activeTab === 'recharge') {
          this.queryParams.dealType = 1;
        } else if (this.activeTab === 'order') {
          this.queryParams.dealType = 2;
        }

        this.dealCompanyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 下载文件 */
// 文件下载处理
    handleDownload(row) {
      const a = document.createElement('a')
      var url = row.invoiceFile;
      a.setAttribute('href',  "https://zsky.lytx.net.cn" + url)
      a.click()
    },

    /** 查询发票列表 */
    getList() {
      this.loading = true;
      listInvoice(this.queryParams).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        invoiceId: null,
        orderId: null,
        invoiceType: null,
        invoiceTitle: null,
        invoiceContent: null,
        invoiceAmount: null,
        invoiceTaxNo: null,
        invoiceTax: null,
        companyName: null,
        invoiceFile: null,
        companyAddress: null,
        contacts: null,
        companyPhone: null,
        bankName: null,
        bankAccount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 表格选择事件 */
    handleRowClick(row) {
      console.log("点击的数据" + JSON.stringify(row));
      // 当用户点击表格行时，将该行数据填充到表单中
      this.form.companyName = row.companyName;
      this.form.invoiceType = row.invoiceType;
      this.form.invoiceTitle = row.invoiceTitle;
      this.form.invoiceTaxNo = row.invoiceTaxNo;
      this.form.companyAddress = row.companyAddress;
      this.form.contacts = row.contacts;
      this.form.companyPhone = row.companyPhone;
      this.form.contactsPhone = row.contactsPhone;
      this.form.bankName = row.bankName;
      this.form.bankAccount = row.bankAccount;
      this.form.bankNum = row.bankNum;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const invoiceId = row.invoiceId || this.ids
      getInvoice(invoiceId).then(response => {
        this.form = response.data;
        this.form.invoiceAmount = fenToYuan(this.form.invoiceAmount)
        this.open = true;
        this.title = "修改发票";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.invoiceAmount = (this.form.invoiceAmount * 100)
        console.log("金额 ======= " + this.form.invoiceAmoun)
        if (valid) {

          // 如果用户选择了抬头，则使用所选抬头的信息
          if (this.selectedHeader) {
            this.form.invoiceTitle = this.selectedHeader.invoiceTitle;
            this.form.invoiceTaxNo = this.selectedHeader.invoiceTaxNo;
            this.form.companyAddress = this.selectedHeader.companyAddress;
            this.form.contacts = this.selectedHeader.contacts;
            this.form.companyPhone = this.selectedHeader.companyPhone;
            this.form.contactsPhone = this.selectedHeader.contactsPhone;
            this.form.bankName = this.selectedHeader.bankName;
            this.form.bankAccount = this.selectedHeader.bankAccount;
            this.form.bankNum = this.selectedHeader.bankNum;
          }


          if (this.form.invoiceId != null) {
            updateInvoice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getDealList();
            });
          } else {
            addInvoice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDealList();
            });
            updateInvoiceStatus(this.form.dealId).then(response => {
              this.open = false;
              this.getDealList();
            });
          }
        }
      });
    },

    // 查询公司钱包
    getWalletCompanyDatiels(companyId) {
      console.log("chuanru公司id" + companyId);
      getWalletCompany(companyId).then(response => {
          console.log("获取公司钱包信息" + JSON.stringify(response.data));
          this.walletForm = response.data;
          console.log("获取公司钱包信息" + JSON.stringify(this.walletForm));
          this.loading = false;
        }
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const invoiceIds = row.invoiceId || this.ids;
      this.$modal.confirm('是否确认删除发票编号为"' + invoiceIds + '"的数据项？').then(function() {
        return delInvoice(invoiceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('consumer/invoice/export', {
        ...this.queryParams
      }, `invoice_${new Date().getTime()}.xlsx`)
    },
    /** 开票按钮操作 */
    replayInvoice(row) {
      this.reset();
      this.open = true;
      this.title = "添加发票"
      this.form = {
        invoiceId: null,
        dealId: row.dealId,
        orderId: row.orderId,
        invoiceType: null,
        invoiceTitle: null,
        invoiceContent: null,
        invoiceAmount: null,
        invoiceTaxNo: null,
        invoiceTax: null,
        companyName: null,
        invoiceFile: null,
        companyAddress: null,
        contacts: null,
        companyPhone: null,
        bankName: null,
        bankAccount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        status: null
      };
      console.log("开票按钮操作" + this.form.orderId);
    },
  }
};
</script>
<style scoped>
.center-tabs {
  display: flex;
  justify-content: center;
}
.center-tabs .el-tabs__header::after {
  width: 100%;
}
</style>
